﻿CREATE PROCEDURE [Cucina].[SP_ComandeDaStampare_L]
	@GracePeriod int,
	@GraceCheckInPeriod int
AS
	SELECT C.ComandaID, PuntoDistribuzioneID
	FROM Cucina.Comanda C
	LEFT JOIN Cucina.ComandaCheckIn CI
		ON C.ComandaID = CI.ComandaID	
	LEFT JOIN Cucina.ComandaStampaRemota CS
		ON C.ComandaID = CS.ComandaID
	WHERE 
		C.IsStampaRemotaRichiesta = 1 
		AND (C.IsCheckInRichiesto = 0 OR CI.ComandaCheckInID IS NOT NULL)
		AND C.DataOra < DATEADD(second, -@GracePeriod, GETDATE()) 
		AND (CI.DataOra IS NULL OR C.DataOra < DATEADD(second, -@GraceCheckInPeriod, GETDATE()))
		AND CS.ComandaStampaRemotaID IS NULL
		AND C.ComandaID NOT IN (SELECT ComandaID FROM Cucina.ComandaDeleted)
		AND C.ComandaID NOT IN (SELECT ComandaID FROM Cucina.ComandaLocked)
RETURN 0